<?php
include("../../includes/global_files/tables.inc");
include(DOCINCLUDES."global_files/global_locale.inc");
include(DOCINCLUDES."global_files/global_html.inc");
include(DOCINCLUDES."global_files/report_php.inc");
include(DOCINCLUDES."global_files/tables.inc");
include(DOCINCLUDES."global_files/global_session.inc");
include(DOCINCLUDES."global_files/form_php.inc");
// include(DOCINCLUDES."global_files/global_filter_functions.inc");
require_once("global_files/global_pgsql.inc");
 
 
$page = new cPage();
$form = new cForm();
$db = new cDatabase();
$page->header_path="../../";
//get customization id from GET
$customization_id=$_GET["customization_id"];
$report_status=$_GET["action"];
$company_id=$_SESSION["search_path"];

//set the title to report name

	$db->query="select
			report_id,
			report_name
			from
			$master_report_table
			where report_id=(select
					report_id
					from
					$sys_report_customization_table
					where
					customization_id=$customization_id
					)";
	$db->runQuery();
	$db_report_name_array=$db->returnArrays();
	$report_name=$db_report_name_array[0]["report_name"];
	$report_id=$db_report_name_array[0]["report_id"];

$page->doHeaderHtml();
$page->doCentreHtml();
$page->title=$page->heading="Report Filter Conditions";

			 $db->query="select
					column_id,
					display_name

					from
					$report_customization_table

					where
					customization_id=$customization_id
					and is_group='f'";
			$db->runQuery();
			$available_columns_array=$db->returnArrays();

			$db->query="select
					column_id,
					display_name

					from
					$report_customization_table

					where
					customization_id=$customization_id and
					is_group='t'";
			$db->runQuery();
			$selected_columns_array=$db->returnArrays();

$query_string=array("company_id"=>$company_id);
$query_string_summary_report=array_merge($query_string,array("report"=>"summary_report"));


        echo "<div align=\"center\">";

//call getFilters function to display filters for this customization id
echo "<form name=\"report_constraint_selection\" method=\"post\" action=\"report_page.php\" onsubmit=\"posted_values1(report_constraint_selection.selectedcolumns);\">";

$constraint_array=getFilters($customization_id);

$form_elements[0]['Available Columns']=
	$form->generateSelectMenu("availablecolumns",$_POST["availablecolumns"],$available_columns_array,"","5","yes","","xnarrow");

$form_elements[0]['Selection']=
	$form->generateInputTag("button",array("name"=>"select","title"=>"Click here to move right","class"=>"rightarrow","accesskey"=>"3","onClick"=>"MoveOption(report_constraint_selection.availablecolumns, report_constraint_selection.selectedcolumns);"))."<br>";

$form_elements[0]['Selection'].=
	$form->generateInputTag("button",array("name"=>"deselect","title"=>"Click here to move left","class"=>"leftarrow","accesskey"=>"3","onClick"=>"MoveOption(report_constraint_selection.selectedcolumns, report_constraint_selection.availablecolumns);"));


$form_elements[0]['Selection'].=
	"<br>".$form->generateInputTag("button",array("name"=>"show","accesskey"=>"3","class"=>"sort","onClick"=>"sortSelect(report_constraint_selection.selectedcolumns);","size"=>"4"));

$form_elements[0]['Selected Columns']=
	$form->generateSelectMenu("selectedcolumns",$_POST["selectedcolumns"],$selected_columns_array,"","5",true,"","xnarrow");

$form_elements[0]['Display Order']=
	 " ".$form->generateInputTag("button",array("name"=>"moveup","title"=>"Click here to move up","class"=>"uparrow","accesskey"=>"3","onClick"=>"moveOptionUp(report_constraint_selection.selectedcolumns)"))."<br>";

$form_elements[0]['Display Order'].=
	" ".$form->generateInputTag("button",array("name"=>"movedown","title"=>"Click here to move down","class"=>"downarrow","accesskey"=>"3","onClick"=>"moveOptionDown(report_constraint_selection.selectedcolumns);"));
echo "<br>";
echo "<h3>Group Conditions</h3>";
doHorizontalTable($form_elements,"20%","","",true,false,"","general_table");
echo "<br>";
	$group 	= $group_array[0]["group"];
	$sort  	= $group_array[0]["sort"];
	$db->query="select
						view_name

						from
						$master_report_table

						where
						report_id=$report_id";
	$db->runQuery();
	$report_details_array=$db->returnArrays();
	$table_name=$report_details_array[0]["table_view_name"];

		//for date condition

	$db->query="select column_name from information_schema.columns where table_name='$table_name' and table_schema='".$company_id."' and data_type in ('date')";
	$db->runQuery();
	$date_condition_array=$db->returnArrays();
	if($date_condition_array)
	{
	foreach($date_condition_array as $key=>$value)
		{
		$db->query="select display_name from $master_report_customization_table where column_id=(select column_id from $master_column_mapping_table where db_column_name='".$value[column_name]."' and report_id=$report_id)";
		$db->runQuery();
		$db_date_display_array=$db->returnArrays();
		$date_display_array[$key]["column_name"]=$value["column_name"];
		$date_display_array[$key]["display_name"]=$db_date_display_array[0]["display_name"];
		}
	}
	$db->query="select column_name from information_schema.columns where table_name='$table_name' and table_schema='".$_SESSION[search_path]."' and data_type in ('integer','numeric')";
	$db->runQuery();
	$number_condition_array=$db->returnArrays();
	if($number_condition_array)
	{
	foreach($number_condition_array as $key=>$value)
		{
		$db->query="select display_name from $master_report_customization_table where column_id=(select column_id from $master_column_mapping_table where db_column_name='".$value[column_name]."' and report_id=$report_id)";
		$db->runQuery();
		$db_number_display_array=$db->returnArrays();
		$number_display_array[$key]["column_name"]=$value["column_name"];
		$number_display_array[$key]["display_name"]=$db_number_display_array[0]["display_name"];
		}
	}
	$date_selection_table[0]["Date Type"]=
		$form->generateSelectMenu("datecondition",$_POST["datecondition"],$date_display_array,"","",true);

		$link="<a href=\"javascript:show_calendar('report_constraint_selection.from_date');\"
onmouseover=\"window.status='Date Picker';return true;\" onmouseout=\"window.status='';return true;\"><img
src=\"".$page->header_path."images/calendar.gif\" width=\"16\" height=\"16\" border=\"0\"></a>";

	$date_selection_table[0]["From"]=
	$form->generateInputTag("text",array("name"=>"from_date","value"=>$from_date,"size"=>"11","maxlength"=>"10"),"",$link);

		$link="<a href=\"javascript:show_calendar('report_constraint_selection.to_date');\"
onmouseover=\"window.status='Date Picker';return true;\" onmouseout=\"window.status='';return true;\"><img
src=\"".$page->header_path."images/calendar.gif\" width=\"16\" height=\"16\" border=\"0\"></a>";

	$date_selection_table[0]["To"]=
		$form->generateInputTag("text",array("name"=>"to_date","value"=>"$to_date","size"=>"11","maxlength"=>"10"),"",$link);

	$number_selection_table1[0]["Number Type"]=
		$form->generateSelectMenu("numbercondition",$_POST["numbercondition"],$number_display_array,"","",true);


	$number_selection_table1[0]["Greater Than >"]=
	$form->generateInputTag("text",array("name"=>"from_no","value"=>$from_date1,"size"=>"11","maxlength"=>"10"),"");

	$number_selection_table1[0]["Less Than <"]=
	$form->generateInputTag("text",array("name"=>"to_no","value"=>"$to_date1","size"=>"11","maxlength"=>"10"),"");
	$selection_table[0]["Date Condition"]=createHorizontalTable($date_selection_table,"","","",true,false,"","general_table");
	$selection_table[0]["Number Condition"]=createHorizontalTable($number_selection_table1,"","","",true,false,"","general_table");
	doHorizontalTable($selection_table,"90%","","",true,false,"","general_table");
	echo "<br>";
		echo $form->generateInputTag("hidden",array("name"=>"customization_id","value"=>"$customization_id"));
		echo $form->generateInputTag("hidden",array("name"=>"report_id","value"=>"$report_id"));
		echo $form->generateInputTag("hidden",array("name"=>"action","value"=>"$report_status"));
		echo "<div style=\"width:20%;left:100px;position:absolute;\">";
		$db->query="select customization_name from $sys_report_customization_table where customization_id=$customization_id";
		$db->runQuery();
		$cus_name_array=$db->returnArrays();
		$customization_name=$cus_name_array[0]["customization_name"];
		if(strtolower($customization_name)!="default")
			echo "Save This Setting &nbsp;".$form->generateInputTag("checkbox",array("name"=>"save_setting"));
		echo "</div>";
		echo "<div align=\"center\" >";
		echo $form->generateInputTag("button",array("name"=>"exit","value"=>"Exit","onclick"=>"javascript:window.open('report_page?report_id=$report_id&customization_id=$customization_id');"))." ";
		echo " ".$form->generateInputTag("submit",array("accesskey"=>"3","name"=>"show","value"=>"Show Report"))."";
        	echo "<input name=\"selected_columns\" type=\"hidden\" value=\"\">";
		echo "</div></form>";


/*function getFilter(integer $customization_id)

	parameter : one- customization id,

	function : get all filters for this customization id from database and display
	filters in screen.

	return : constraint array for grouping.*/

function getFilters($customization_id)
	{
	global $db,$form,$sys_master_filter,$sys_report_filter_table,$master_column_mapping_table,$master_report,$sys_filter_customization_table,$sys_report_customization_table,$master_report_table,$sys_master_filter_table,$company_id;



	//query to fetch all filters for this particular report_id if no customization_id is active
	if($customization_id)
		{
		$db->query="select
					sfc.filter_id as filter_id,
					smf.filter_name as filter_name,
					smf.filter_table_join,
					smf.form_field_name[1] as form_field_name1,
					smf.form_field_name[2] as form_field_name2,
					sfc.filter_display_name as form_display,
					smf.fetch_condition,
					smf.order_by,
					sfc.filter_order,
					sfc.default_value

					from $sys_filter_customization_table sfc join $sys_master_filter_table smf on sfc.filter_id=smf.filter_id where sfc.customization_id=$customization_id order by sfc.filter_order ;";
		$db->runQuery();
		$filter_id_array=$db->returnArrays();
		}



	$c=count($filter_id_array);


	for($i=0;$i<$c;$i++)
		{
		if($filter_id_array[$i]["default_value"])
			$default_array=explode('}',$filter_id_array[$i]["default_value"]);

		// forming where and order by clause for filter query

		if($filter_id_array[$i]["fetch_condition"])
			$condition= "where ". $filter_id_array[$i]["fetch_condition"]."";
		if($filter_id_array[$i][order_by])
			$order_by="order by ".$filter_id_array[$i]["order_by"]."";

		// query to fetch filter

		$db->query="select

				".$filter_id_array[$i]["form_field_name1"]."

				from
				".$filter_id_array[$i][filter_table_join]." ".$condition." ".$order_by .";";

		$db->runQuery();
		$filter_array=$db->returnArrays();

		//query to fetch group column element using master_column_mapping and sys_report_filter

		$db->query="select

				script_variable_name

				from
				$master_column_mapping_table
				where column_id in (select
						group_column
						from
						$sys_report_filter_table
						where filter_id=".$filter_id_array[$i][filter_id].
						");";
		$db->runQuery();
		$group_column_array=$db->returnArrays();

		///constraint array for grouping

		$constraint_array[$filter_id_array[$i][form_display]]=$group_column_array[0]["script_variable_name"];
		/// if no of filter greater than 7 then show filter in next row(for our convenience)
			$table[0][$filter_id_array[$i]["form_display"]]=
				$form->generateSelectMenu($filter_id_array[$i]["filter_name"]."[]",$default_array,$filter_array,"All",7,true,"","xnarrow");
		

		unset($condition,$order_by,$filter_array,$default_array);
		}
	echo "<br><div align=\"center\" style=\"width:90%;overflow:auto;\" >";
		doHorizontalTable($table,"10%","","",true,false,"","general_table");
	echo "</div>";

	return $constraint_array;

	}

function getGroups($group_name,$group_order,$sort_name,$sort_order,$constraint_array)
	{
	//group.inc file replaced
	global $db,$form,$master_column_mapping_table,$master_report_customization_table;

	formatConstraintArray($constraint_array);


$no_of_group_by=($_SESSION["guser_preferences"]["no_of_group_by"])?$_SESSION["guser_preferences"]["no_of_group_by"]:2;
$no_of_sort_by=($_SESSION["guser_preferences"]["no_of_sort_by"])?$_SESSION["guser_preferences"]["no_of_sort_by"]:1;
for($g=0;$g<$no_of_group_by;$g++)
	{
	$no_g=$g+1;
	$group_form_formatting["Group ".$no]="text-align:center; width:150px";
	if(!$group_order[0])
		{
		$group_order[0]="ascending";
		}
	$constraint_selection_table[0]["Group ".$no_g]="<label id=\"group\" accesskey=\"G\">";
	$constraint_selection_table[0]["Group ".$no_g].=$form->generateSelectMenu("group_name[$g]",$group_name[$g],$constraint_array,"","",true);
	$constraint_selection_table[0]["Group ".$no_g].="</label>";
	$ascending_order_selected=($group_order[0]=="ascending")?"checked":"";
	$constraint_selection_table[0]["Group ".$no_g].="<br><input type=\"radio\" name=\"group_order[$g]\" value=\"ascending\" $ascending_order_selected >"."Asc";
	$descending_order_selected=($group_order[1]=="descending")?"checked":"";
	$constraint_selection_table[0]["Group ".$no_g].="<input type=\"radio\" name=\"group_order[$g]\" value=\"descending\" $descending_order_selected >"."Desc";
	}
for($s=0;$s<$no_of_sort_by;$s++)
	{
	$no_s=$s+1;
	if(!$sort_order[0])
		{
		$sort_order[0]="ascending";
		}
	//for sort column
	$constraint_selection_table[0]["Sort ".$no_s]=$form->generateSelectMenu("sort_name[$s]",$sort_name[$s],$constraint_array,"","","");
	$ascending_order_selected=($sort_order[0]=="ascending")?"checked":"";
	$constraint_selection_table[0]["Sort ".$no_s].="<br><input type=\"radio\" name=\"sort_order[$s]\" value=\"ascending\" $ascending_order_selected >"."Asc";
	$descending_order_selected=($sort_order[1]=="descending")?"checked":"";
	$constraint_selection_table[0]["Sort ".$no_s].="<input type=\"radio\" name=\"sort_order[$s]\" value=\"descending\" $descending_order_selected >"."Desc";
	}

// 	$date_condition_array["deldate"]="deldate";
// 	$date_condition_array["plandate"]="plandate";
// 	$date_condition_array["xfac"]="xfac";
	//formatConstraintArray($date_condition_array);

	//include(DOCINCLUDES."global_files/group_form.inc");
       	doHorizontalTable($constraint_selection_table,"","",$group_form_formatting);
	$group_array[0]["group"] =$group;
	$group_array[0]["sort"]  =$sort;
	return $group_array;
	}


?>
<script language="javascript" >

function MoveOption(objSourceElement, objTargetElement)
	{
	var values= new Array();
	var aryTempSourceOptions = new Array();
	var x = 0;
	var selected_item=-1;
	//looping through source element to find selected options
	for (var i = 0,flag=0; i < objSourceElement.length; i++)
		{
		    if (objSourceElement.options[i].selected)
	    		{
	    
			var intTargetLen = objTargetElement.length++;
			objTargetElement.options[intTargetLen].text = objSourceElement.options[i].text;
			objTargetElement.options[intTargetLen].value = objSourceElement.options[i].value;
			selected_item=i+1;
			flag++;
			
	    		}
	    	else
	    		{
			//storing options that stay to recreate select element
			var objTempValues = new Object();
			objTempValues.text = objSourceElement.options[i].text;
			objTempValues.value = objSourceElement.options[i].value;
			aryTempSourceOptions[x] = objTempValues;
			x++;
	   		}

		}
	

	//resetting length of source
	objSourceElement.length = aryTempSourceOptions.length;
	//looping through temp array to recreate source select element

	for (var i = 0; i < aryTempSourceOptions.length; i++)
		{
		objSourceElement.options[i].text = aryTempSourceOptions[i].text;
		objSourceElement.options[i].value = aryTempSourceOptions[i].value;
		objSourceElement.options[i].selected = false;
		}
	if(selected_item!=-1)
		{
		if(selected_item>flag)
			selected_item=selected_item-flag;
		else
			selected_item=flag-selected_item;
		objSourceElement.options[selected_item].selected=true;
		}
   	}

       	function posted_values(objTargetElement)
	{
		var selected_filters;
		var values=new Array();
		for (var i = 0; i < objTargetElement.length; i++)
			{
			values[i]= objTargetElement.options[i].value;
			}
		   selected_filters=values.toString();
		   document.report_constraint_selection.selected_filters.value=selected_filters;

	}
	function posted_values1(objTargetElement)
	{
		var selected_columns;
		var values=new Array();
		for (var i = 0; i < objTargetElement.length; i++)
			{
			values[i]= objTargetElement.options[i].value;
			}
		   selected_columns=values.toString();
		   document.report_constraint_selection.selected_columns.value=selected_columns;

	}

	function sortSelect(objTargetElement)
	{
	var o = new Array();
	for (var i=0; i<objTargetElement.options.length; i++)
		{
		o[o.length] = new Option( objTargetElement.options[i].text,objTargetElement.options[i].value, objTargetElement.options[i].defaultSelected, objTargetElement.options[i].selected) ;
		}
	if (o.length==0)
	 	{
	  	return;
	  	}
	o = o.sort(
		function(a,b)
			{
			if ((a.text+"") < (b.text+"")) { return -1; }
			if ((a.text+"") > (b.text+"")) { return 1; }
			return 0;
			}
		);

	for (var i=0; i<o.length; i++)
		{
		objTargetElement.options[i] = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
		}
	}

	function hasOptions(obj)
	{
	if (obj!=null && obj.options!=null)
		 {
		 return true;
		 }
	return false;
	}

	function swapOptions(obj,i,j)
	{
		var o = obj.options;
		var i_selected = o[i].selected;
		var j_selected = o[j].selected;
		var temp = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
		var temp2= new Option(o[j].text, o[j].value, o[j].defaultSelected, o[j].selected);
		o[i] = temp2;
		o[j] = temp;
		o[i].selected = j_selected;
		o[j].selected = i_selected;
	}

	function moveOptionUp(obj)
	{
	if (!hasOptions(obj))
		{
		return;
		}
		for (i=0; i<obj.options.length; i++)
		{
			if (obj.options[i].selected)
			{
				if (i != 0 && !obj.options[i-1].selected)
				{
					swapOptions(obj,i,i-1);
					obj.options[i-1].selected = true;
				}
			}
		}
	}
	function moveOptionDown(obj)
	{
	if (!hasOptions(obj))
		{
		return;
		}
		for (i=obj.options.length-1; i>=0; i--)
			{
			if (obj.options[i].selected)
				{
					if (i != (obj.options.length-1) && ! obj.options[i+1].selected)
					{
						swapOptions(obj,i,i+1);
						obj.options[i+1].selected = true;
					}
				}
			}
	}

function loadinparent(url, closeSelf)
	{
	//self.opener.location = url;
	//document.report_constraint_selection.submit();
		//window.opener.close();
		window.resizeTo(1024,768);
//window.opener.close( );

	//if(closeSelf)
	//	self.close();
	}
	function closeWindow()
	{
	window.open('','_parent','');

	//window.close();
	}
// function Toggle(item)
// 	{
// 	obj=document.getElementById(item);
// 	visible=(obj.style.display!="none")
// 	if (visible)
// 		{
// 		obj.style.display="none";
//    		}
// 	 else
// 		{
//       		obj.style.display="block";
// 		}
// 	}
</script>
